<?php
require_once '../utils/Database.php';
require_once '../utils/WeChatAuth.php';
require_once '../utils/Response.php';

$db = new Database();
$auth = new WeChatAuth();

$user = $auth->getCurrentUser();
if (!$user) {
    Response::authError('请先登录');
}

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'POST':
        // 志愿者报名
        $data = [
            'user_id' => $user['id'],
            'name' => $input['name'],
            'gender' => $input['gender'],
            'phone' => $input['phone'],
            'student_id' => $input['student_id'] ?? '',
            'department' => $input['department'] ?? '',
            'grade' => $input['grade'] ?? '',
            'experience' => $input['experience'] ?? '',
            'available_time' => $input['available_time'] ?? '',
            'self_introduction' => $input['self_introduction'] ?? '',
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        // 检查是否已经报名
        $existing = $db->fetchOne(
            "SELECT id FROM volunteer_applications WHERE user_id = ? AND status IN (0, 1)",
            [$user['id']]
        );
        
        if ($existing) {
            Response::error('您已提交过志愿者申请，请勿重复提交');
        }
        
        $applicationId = $db->insert('volunteer_applications', $data);
        
        if ($applicationId) {
            Response::success(['application_id' => $applicationId], '志愿者申请提交成功');
        } else {
            Response::error('申请提交失败');
        }
        break;
        
    case 'GET':
        if (isset($_GET['action'])) {
            switch ($_GET['action']) {
                case 'status':
                    // 查询申请状态
                    $application = $db->fetchOne(
                        "SELECT * FROM volunteer_applications WHERE user_id = ? ORDER BY created_at DESC LIMIT 1",
                        [$user['id']]
                    );
                    
                    if ($application) {
                        Response::success($application, '获取成功');
                    } else {
                        Response::success(null, '暂无申请记录');
                    }
                    break;
                    
                default:
                    Response::error('无效的操作');
            }
        } else {
            Response::error('缺少action参数');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}
?>